package com.zhixue.auth.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhixue.auth.ucenter.mapper.*;
import com.zhixue.auth.ucenter.model.dto.*;
import com.zhixue.auth.ucenter.model.po.XcMenu;
import com.zhixue.auth.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Auther: 李 力
 * @Date: 2025/5/12
 * @Description: com.zhixue.auth.ucenter.service.impl
 * @version: 1.0
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private XcUserMapper userMapper;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private XcMenuMapper xcMenuMapper;

    //传入的请求认证参数就是AuthParamsDto
    @Override
    public UserDetails loadUserByUsername(String params) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(params)) {
            throw new RuntimeException("参数is null");
        }
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(params, AuthParamsDto.class);
        } catch (Exception exception) {
            throw new RuntimeException("请求认证参数不合法");
        }
        String authType = authParamsDto.getAuthType();
        if (StringUtils.isEmpty(authType)) {
            throw new RuntimeException("认证类型参数为空");
        }
        authType = authType + "_authService";
        AuthService authService = applicationContext.getBean(authType, AuthService.class);
        XcUserExt xcUserExt = authService.execute(authParamsDto);

        return getUserPrincipal(xcUserExt);
    }

    private UserDetails getUserPrincipal(XcUserExt user) {
        // 用户权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(user.getId());
        List<String> permissions = new ArrayList<>();
        if (xcMenus != null && !xcMenus.isEmpty()) {
            for (XcMenu xcMenu : xcMenus) {
                permissions.add(xcMenu.getCode());
            }
        }
        String[] authorities = permissions.toArray(new String[0]);
        String password = user.getPassword();
        //为了安全在令牌中不放密码
        user.setPassword(null);
        //将user对象转json
        String userString = JSON.toJSONString(user);
        //创建UserDetails对象
        return User.withUsername(userString).password(password).authorities(authorities).build();
    }
}
